<script>
	import {
		clearStorage,
		getStorage,
		removeStorage
	} from '@/util/auth.js';
	import {
		getWxLoginCode
	} from '@/util/user.js'
	import config from '@/config.js';
	export default {
		onLaunch: function() {
			uni.loadFontFace({
				source: 'url("https://job-supermarket-1306862033.cos.ap-chengdu.myqcloud.com/uniapp/%E6%96%B9%E6%AD%A3%E6%B1%89%E7%9C%9F%E5%B9%BF%E6%A0%87%E7%AE%80%E4%BD%93.TTF")',
				family: 'FangZhengHanZhenGuangBiaoJianTi',
				global: true
			})
			uni.loadFontFace({
				source: 'url("https://jt-charge-pile-1306862033.cos.ap-chengdu.myqcloud.com/uniapp/home/lengku.ttf")',
				family: 'lengku',
				global: true,
			})
			
			// 设置应用保持活跃状态，防止被系统回收
			// #ifdef APP-PLUS
			try {
				// 设置应用保持屏幕常亮（可选）
				plus.screen.lockOrientation("portrait-primary");
				
				// 监听系统音频会话变化
				if (uni.getSystemInfoSync().platform === 'ios') {
					// iOS特定的音频会话设置
					console.log('iOS平台，设置音频会话');
				} else if (uni.getSystemInfoSync().platform === 'android') {
					// Android特定设置
					console.log('Android平台，设置保活机制');
				}
			} catch(e) {
				console.log('平台特定设置失败:', e);
			}
			// #endif
			
			// 不再自动申请电池优化权限，改为通过弹窗引导用户操作
			
			uni.$on('onlineChange',(online)=>{
				if(online){
					if(this.voiceBroadcastTask){
						return;
					}
					this.createWebSocketTask();
				}else{
					this.closeWebSocket()
					this.closeInterval();
				}
			})
			uni.$on('tokenChange',(token)=>{
				if(!token){
					this.closeInterval();
					this.closeWebSocket();
				}
			})
			this.createBroadcastIns();
			
			// 注释掉自动测试音频播放
			// setTimeout(() => {
			// 	this.testAudioPlay();
			// }, 3000);
		},
		onExit(){
			this.closeInterval();
			this.closeWebSocket();
			if (this.connectionCheckTimer) {
				clearInterval(this.connectionCheckTimer);
				this.connectionCheckTimer = null;
			}
		},
		onHide() {
			console.log('App进入后台');
			// 记录当前在线状态，以便恢复时使用
			this.wasOnline = this.$store.getters['push/online'];
			this.wasConnected = this.voiceBroadcastTask !== null;
			
			// 记录WebSocket状态
			if (this.voiceBroadcastTask) {
				console.log('记录WebSocket连接状态');
				this.wasSocketConnected = true;
			} else {
				this.wasSocketConnected = false;
			}
			
			// 不主动关闭WebSocket，让系统决定是否保持连接
			// 但停止心跳定时器以节省资源
			this.closeInterval();
			
			// 暂停定期连接检查，节省后台资源
			if (this.connectionCheckTimer) {
				clearInterval(this.connectionCheckTimer);
				this.connectionCheckTimer = null;
			}
			
			// 记录当前时间，用于判断后台时长
			this.backgroundTime = new Date().getTime();
		},
		onShow() {
			console.log('App恢复前台');
			const token = this.$store.getters.token;
			
			// 重新创建音频管理器，恢复音频播放能力
			this.createBroadcastIns();
			
			// 计算后台时长
			const backgroundDuration = this.backgroundTime ? (new Date().getTime() - this.backgroundTime) / 1000 : 0;
			console.log(`App在后台运行了${backgroundDuration}秒`);
			
			if (token) {
				// 检查WebSocket连接状态
				const isSocketAlive = this.voiceBroadcastTask && this.voiceBroadcastTask.readyState === 1;
				console.log('WebSocket状态检查:', {
					wasSocketConnected: this.wasSocketConnected,
					currentSocket: !!this.voiceBroadcastTask,
					isSocketAlive: isSocketAlive,
					wasOnline: this.wasOnline
				});
				
				// 只在确实需要重连的情况下重连
				if (this.wasOnline && !isSocketAlive && !this.isReconnecting) {
					console.log('检测到需要重新建立WebSocket连接');
					// 重置重连次数，因为这是用户主动切回前台
					this.restartCount = 0;
					this.closeWebSocket();
					setTimeout(() => {
						this.createWebSocketTask();
					}, 1000);
				}
				
				// 更新推送状态，但不主动改变在线状态
				this.$store.dispatch('push/getPushStatus')
					.catch(err => {
						console.log('获取推送状态失败，保持当前状态', err);
					});
			}
			
			// 清除背景时间记录
			this.backgroundTime = null;
		},
		data(){
			return{
				voiceBroadcastTask:null,
				heartbeatTimer:null,
				heartbeatTime:null,
				broadcastIns:null,
				
				closeBroadcast:false,
				
				restartCount:0,
				
				// 添加状态记录变量
				wasOnline: false,
				wasConnected: false,
				wasSocketConnected: false,
				backgroundTime: null,
				connectionCheckTimer: null,
				isReconnecting: false,
				
				// 添加消息去重相关变量
				lastMessageId: null,
				lastMessageTime: null,
				messageCache: new Set(), // 用于存储最近的消息ID
			}
		},
		methods: {
			restartWebSocket(){
				// 如果已经在重连中，不要重复触发
				if(this.isReconnecting) {
					console.log('已经在重连中，跳过本次重连');
					return;
				}
				
				this.$store.commit('push/SET_READY',false);
				this.closeInterval();
				this.closeWebSocket();
				
				this.restartCount++;
				if(this.restartCount > 5){
					console.log('重连次数超过限制，停止重连');
					this.$store.dispatch('push/handleOnline',2);
					this.showToast('尝试连接服务器失败，请重试');
					this.restartCount = 0;
					this.isReconnecting = false;
					return;
				}
				
				console.log(`开始第${this.restartCount}次重连`);
				this.isReconnecting = true;
				
				// 使用setTimeout确保有足够的间隔
				setTimeout(() => {
					this.createWebSocketTask();
					this.isReconnecting = false;
				}, 3000);
			},
			closeInterval(){
				if(this.heartbeatTimer){
					clearInterval(this.heartbeatTimer);
				}
				this.heartbeatTime=null;
			},
			closeWebSocket(){
				if(this.voiceBroadcastTask){
					this.voiceBroadcastTask.close({
						code:1,
						reason:'closeBroadcast'
					})
				}
				this.voiceBroadcastTask=null;
				this.closeBroadcast=true;
			},
			createBroadcastIns(){
				// 重新创建背景音频管理器
				if(this.broadcastIns) {
					try {
						this.broadcastIns.stop();
					} catch(e) {
						console.log('停止音频出错', e);
					}
				}
				
				console.log('创建背景音频管理器');
				this.broadcastIns = uni.getBackgroundAudioManager();
				
				// 设置基本属性
				this.broadcastIns.title = "语音播报"; // iOS需要设置title才能后台播放
				this.broadcastIns.singer = "播报系统";
				this.broadcastIns.epname = "语音提醒";
				this.broadcastIns.coverImgUrl = "https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/face.png"; 
				
				// 其他配置
				this.broadcastIns.obeyMuteSwitch = false; // 不遵循静音开关
				
				console.log('背景音频管理器创建完成');
			},
			createWebSocketTask(){
				// 如果已经有活跃的连接，不要重复创建
				if(this.voiceBroadcastTask && this.voiceBroadcastTask.readyState === 1) {
					console.log('WebSocket连接已存在且活跃，跳过创建');
					return;
				}
				
				this.closeWebSocket();
				this.closeInterval();
				
				uni.showLoading({
					title: this.restartCount>0 ? `正在尝试第${this.restartCount}次重新连接` : '正在连接服务器',
				})
				this.closeBroadcast = false;
				
				// 设置WebSocket连接选项
				const socketOptions = {
					url: config.webSocketUrl,
					timeout: 30000, // 30秒连接超时
					header: {
						'content-type': 'application/json'
					},
					success: () => {
						console.log('WebSocket连接请求成功发送');
					},
					fail: (err) => {
						console.log('WebSocket连接失败', err);
						this.restartWebSocket();
					}
				};
				
				// 添加Token到Header
				const token = this.$store.getters.token;
				if (token) {
					socketOptions.header['Authorization'] = token;
				}
				
				console.log('准备建立WebSocket连接:', config.webSocketUrl);
				this.voiceBroadcastTask = uni.connectSocket(socketOptions);
				
				this.voiceBroadcastTask.onOpen(() => {
					console.log('WebSocket连接已建立');
					uni.hideLoading();
					this.restartCount = 0;
					this.isReconnecting = false;
					
					// 发送首次心跳
					this.sendHeartbeat();
					
					// 设置心跳定时器
					this.heartbeatTimer = setInterval(() => {
						this.sendHeartbeat();
					}, 20*1000);
					
					this.$store.commit('push/SET_READY', true);
					console.log('设置播报服务状态为开启');
				});
				this.voiceBroadcastTask.onClose((err)=>{
					console.log(err)
					console.log('ws关闭')
					if(!this.closeBroadcast){
						this.restartWebSocket();
					}
					this.closeBroadcast=false;
					this.$store.commit('push/SET_READY',false)
				})
				this.voiceBroadcastTask.onError(()=>{
					console.log('ws错误')
					if(!this.closeBroadcast){
						this.restartWebSocket();
					}
					this.closeBroadcast=false;
					this.$store.commit('push/SET_READY',false)
				})
				this.voiceBroadcastTask.onMessage((params)=>{
					const data = JSON.parse(params.data);
					this.heartbeatTime = new Date().getTime();
					console.log('ws收到消息', data);
					
					// 重置重连计数，因为连接正常
					this.restartCount = 0;
					
					if(data.type === 'payment'){
						// 检查是否是重复消息
						const messageId = data.audioFile; // 使用音频文件名作为消息ID
						const currentTime = new Date().getTime();
						
						// 如果消息在缓存中，说明是重复消息
						if(this.messageCache.has(messageId)) {
							console.log('检测到重复消息，跳过播放:', messageId);
							return;
						}
						
						// 将消息ID添加到缓存
						this.messageCache.add(messageId);
						
						// 清理旧消息（保留最近5分钟的消息）
						setTimeout(() => {
							this.messageCache.delete(messageId);
						}, 5 * 60 * 1000);
						
						uni.$emit('onPaymentMessage');
						
						// 构建完整URL
						const src = config.voiceUrl + data.audioFile;
						console.log('准备播放音频URL:', src);
						
						// 先检查音频文件是否可访问
						uni.request({
							url: src,
							method: 'HEAD',
							success: (res) => {
								console.log('音频文件检查结果:', res.statusCode);
								if(res.statusCode === 200) {
									this.playAudio(src);
								} else {
									console.error('音频文件不存在或无法访问:', src);
								}
							},
							fail: (err) => {
								console.error('检查音频文件失败:', err);
								// 尝试直接播放
								this.playAudio(src);
							}
						});
					} else if(data.type === 'heartbeat') {
						console.log('收到心跳响应');
					}
				})
			},
			// 添加发送心跳的独立方法
			sendHeartbeat() {
				if (!this.voiceBroadcastTask) {
					console.log('无法发送心跳：WebSocket未连接');
					return;
				}
				
				// 检查WebSocket连接状态
				if (this.voiceBroadcastTask.readyState !== 1) {
					console.log('WebSocket连接状态异常，readyState:', this.voiceBroadcastTask.readyState);
					this.restartWebSocket();
					return;
				}
				
				try {
					this.voiceBroadcastTask.send({
						data: JSON.stringify({
							type: 'heartbeat',
							timestamp: new Date().getTime(),
							token: this.$store.getters.token
						})
					});
					
					console.log('心跳发送成功');
					
					// 更新最近心跳时间
					this.heartbeatTime = new Date().getTime();
					
					// 检查心跳响应超时 - 缩短超时时间以便更快发现连接问题
					setTimeout(() => {
						if (this.heartbeatTime && (new Date().getTime() - this.heartbeatTime > 45*1000)) {
							console.log('心跳响应超时，可能连接已断开');
							this.restartWebSocket();
						}
					}, 45*1000);
				} catch (e) {
					console.error('发送心跳失败:', e);
					this.restartWebSocket();
				}
			},
			// 添加测试音频播放方法
			testAudioPlay() {
				console.log('测试音频播放');
				try {
					// 使用本地音频文件进行测试
					const testSrc = "/static/audio/test.wav";
					
					// 直接调用playAudio方法，它会处理所有必要的设置
					this.playAudio(testSrc);
					
				} catch(e) {
					console.error('测试音频播放失败:', e);
					uni.showToast({
						title: '音频播放功能异常',
						icon: 'none'
					});
				}
			},
			// 添加新方法用于播放音频
			playAudio(src) {
				console.log('开始播放音频:', src);
				
				// 每次播放前都重新创建音频管理器，避免被其他应用影响
				this.createBroadcastIns();
				
				// 确保音频播放时设置了所有必要属性
				try {
					// 先停止当前播放
					if(this.broadcastIns) {
						try {
							this.broadcastIns.stop();
						} catch(e) {
							console.log('停止之前的音频失败，继续执行', e);
						}
					}
					
					// 重新设置属性和播放源
					this.broadcastIns.title = "语音播报";
					this.broadcastIns.singer = "播报系统";
					this.broadcastIns.epname = "语音提醒";
					this.broadcastIns.coverImgUrl = "https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/face.png";
					
					// 设置播放错误重试机制
					let retryCount = 0;
					const maxRetries = 3;
					
					const tryPlay = () => {
						console.log(`尝试播放音频，第${retryCount + 1}次`);
						
						// 重新设置错误监听
						this.broadcastIns.onError = (err) => {
							console.error('音频播放错误:', err);
							retryCount++;
							
							if (retryCount < maxRetries) {
								console.log(`播放失败，${1000}ms后重试`);
								setTimeout(() => {
									// 重新创建音频管理器再次尝试
									this.createBroadcastIns();
									this.broadcastIns.title = "语音播报";
									this.broadcastIns.singer = "播报系统";
									this.broadcastIns.epname = "语音提醒";
									this.broadcastIns.coverImgUrl = "https://suzhou-taxi-1306862033.cos.ap-chengdu.myqcloud.com/file/face.png";
									tryPlay();
								}, 1000);
							} else {
								console.error('音频播放重试次数超限，放弃播放');
								uni.showToast({
									title: '语音播报失败',
									icon: 'none',
									duration: 2000
								});
							}
						};
						
						// 设置播放成功监听
						this.broadcastIns.onPlay = () => {
							console.log('音频播放成功');
							retryCount = 0; // 重置重试计数
						};
						
						// 设置播放结束监听
						this.broadcastIns.onEnded = () => {
							console.log('音频播放结束');
						};
						
						// 设置暂停监听
						this.broadcastIns.onPause = () => {
							console.log('音频被暂停');
						};
						
						// 设置停止监听
						this.broadcastIns.onStop = () => {
							console.log('音频被停止');
						};
						
						// 设置src开始播放
						this.broadcastIns.src = src;
						
						// 确保播放
						setTimeout(() => {
							try {
								if(this.broadcastIns.paused) {
									console.log('音频未自动播放，尝试手动播放');
									this.broadcastIns.play();
								}
							} catch(e) {
								console.error('手动播放失败', e);
							}
						}, 500);
					};
					
					// 开始首次尝试播放
					tryPlay();
					
				} catch(e) {
					console.error('播放音频出错', e);
					// 尝试重新创建播放器并播放
					this.createBroadcastIns();
					setTimeout(() => {
						this.broadcastIns.src = src;
					}, 500);
				}
			},
			// 请求忽略电池优化权限（Android）
			requestIgnoreBatteryOptimization() {
				// #ifdef APP-PLUS
				if(uni.getSystemInfoSync().platform === 'android') {
					try {
						const main = plus.android.runtimeMainActivity();
						const packageName = main.getPackageName();
						const powerManager = plus.android.importClass("android.os.PowerManager");
						const pm = main.getSystemService(plus.android.importClass("android.content.Context").POWER_SERVICE);
						
						console.log('检查是否已忽略电池优化');
						// 检查是否已被忽略电池优化
						if(!pm.isIgnoringBatteryOptimizations(packageName)) {
							console.log('申请忽略电池优化');
							// 创建意图，请求忽略电池优化
							const Intent = plus.android.importClass('android.content.Intent');
							const Settings = plus.android.importClass('android.provider.Settings');
							const intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
							intent.setData(plus.android.importClass("android.net.Uri").parse("package:" + packageName));
							
							// 启动意图前标记一下，避免多次触发
							uni.setStorageSync('battery_permission_requesting', 'true');
							
							// 启动意图
							main.startActivity(intent);
							return false; // 表示权限未获得，但已发起请求
						} else {
							console.log('已忽略电池优化');
							return true; // 表示已获得权限
						}
					} catch(e) {
						console.error('申请忽略电池优化失败:', e);
						return false;
					}
				}
				return false;
				// #endif
			},
		}
	}
</script>

<style lang="scss">
	@import url("@/static/iconfont/iconfont.css");

	.FZHZGBJ {
		font-family: 'FangZhengHanZhenGuangBiaoJianTi';
	}

	.LENGKU {
		font-family: 'lengku';
	}

	button {
		padding: 0;
		background: none;
		line-height: normal !important;
	}

	button::after {
		border: none !important;
	}

	view,
	text,
	navigator,
	input,
	picker,
	button,
	scroll-view,
	textarea,
	label,
	image {
		box-sizing: border-box;
	}

	.input-placeholder {
		color: #686868;
		font-weight: normal;
		// display: flex;
		// justify-content: flex-end;
		font-size: 30rpx
	}

	.empty {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #313131;
		font-size: 28rpx;
		margin: 30rpx auto;
	}

	page {
		min-height: calc(100vh - var(--window-bottom) - var(--window-top));
		background: $background-color;
	}

	.page {
		width: 100%;
		min-height: calc(100vh - var(--window-bottom) - var(--window-top));
	}

	.input-placeholder {
		color: #686868;
		font-weight: normal;
	}

	.btn {
		width: 330rpx;
		height: 90rpx;
		border-radius: 60px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn-small {
		width: 160rpx;
		height: 64rpx;
		border-radius: 60px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
	}

	.normal {
		color: #fff;
		background: linear-gradient(to right, #4A8DFF, #4A8DFF);
	}

	.red {
		color: #fff;
		background: #ff3e25;
	}

	.green {
		color: #fff;
		background: #14aa2d;
	}

	.cancel {
		color: $theme-color;
		border: 1px solid $theme-color;
	}

	.disabled {
		color: #fff;
		background: #999;
		border: none;
	}

	.full {
		color: $theme-color;
		background: #EDF3FF;
	}

	image {
		display: block;
	}
</style>